package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.socket.MessageType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.socket.bean.BaseDataPiece;
import com.ruoyi.common.core.domain.entity.socket.bean.BoatMessage;
import com.ruoyi.common.core.domain.entity.socket.bean.WharfInfo;
import com.ruoyi.common.core.domain.entity.system.SysBoat;
import com.ruoyi.common.core.domain.entity.system.SysWharf;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.handler.socket.SocketMessageHandler;
import com.ruoyi.manager.SocketChannelManager;
import com.ruoyi.system.service.ISysBoatService;
import com.ruoyi.system.service.ISysWharfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 景区码头，每个景区可能有1个或多个码头，景区与码头之间属于一对多的关系。Controller
 *
 * @author ruoyi
 * @date 2023-05-22
 */
@RestController
@RequestMapping("/system/wharf")
public class SysWharfController extends BaseController {
    @Autowired
    private ISysWharfService sysWharfService;

    @Autowired
    private ISysBoatService sysBoatService;

    /**
     * 查询景区码头，每个景区可能有1个或多个码头，景区与码头之间属于一对多的关系。列表
     */
//    @PreAuthorize("@ss.hasPermi('system:wharf:list')")
//    @GetMapping("/list")
//    public TableDataInfo list(SysWharf wharf) {
//        startPage();
//        List<SysWharf> list = sysWharfService.selectWharfList(wharf);
//        return getDataTable(list);
//    }
    @GetMapping("/list")
    public AjaxResult list(SysWharf wharf) {
        List<SysWharf> list = sysWharfService.selectWharfList(wharf);
        return success(list);
    }

    /**
     * 导出景区码头，每个景区可能有1个或多个码头，景区与码头之间属于一对多的关系。列表
     */
    @PreAuthorize("@ss.hasPermi('system:wharf:export')")
    @Log(title = "景区码头管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysWharf wharf) {
        List<SysWharf> list = sysWharfService.selectWharfList(wharf);
        ExcelUtil<SysWharf> util = new ExcelUtil<SysWharf>(SysWharf.class);
        util.exportExcel(response, list, "景区码头管理数据");
    }

    /**
     * 获取景区码头管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:wharf:query')")
    @GetMapping(value = "/{wharfId}")
    public AjaxResult getInfo(@PathVariable("wharfId") Long wharfId) {
        return success(sysWharfService.selectWharfByWharfId(wharfId));
    }

    /**
     * 新增景区码头，每个景区可能有1个或多个码头，景区与码头之间属于一对多的关系。
     */
    @PreAuthorize("@ss.hasPermi('system:wharf:add')")
    @Log(title = "景区码头管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysWharf wharf) {
        wharf.setCreateBy(getUsername());
        wharf.setCreateTime(new Date());
        int rows = sysWharfService.insertWharf(wharf);

        return toAjax(rows);
    }

    /**
     * 修改景区码头，每个景区可能有1个或多个码头，景区与码头之间属于一对多的关系。
     */
    @PreAuthorize("@ss.hasPermi('system:wharf:edit')")
    @Log(title = "景区码头管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysWharf wharf) {
        wharf.setUpdateBy(getUsername());
        wharf.setUpdateTime(new Date());
        int rows = sysWharfService.updateWharf(wharf);
        if (rows > 0 && Objects.nonNull(wharf.getLat()) && Objects.nonNull(wharf.getLon()) && Objects.nonNull(wharf.getWharfCode())) {
            SocketMessageHandler.sendWharfInfoToAllOnlineBoatOfAssignedScenic(wharf);
        }
        return toAjax(rows);
    }

    /**
     * 删除景区码头，每个景区可能有1个或多个码头，景区与码头之间属于一对多的关系。
     */
    @PreAuthorize("@ss.hasPermi('system:wharf:remove')")
    @Log(title = "景区码头管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{scenicId}/{wharfIds}")
    public AjaxResult remove(@PathVariable("scenicId") Long scenicId, @PathVariable("wharfIds") Long[] wharfIds) {
        int rows = sysWharfService.deleteWharfByWharfIds(wharfIds);
        if (rows > 0) {
            //取第一个被删除的码头id，一般一次只会删除一个码头
            Long firstWharfId = wharfIds[0];
            //去船只表中找出对应景区id和码头id的所有船只列表
            SysBoat sysBoat = new SysBoat();
            sysBoat.setScenicId(scenicId);
            sysBoat.setWharfId(firstWharfId);
            List<SysBoat> boatList = sysBoatService.selectSysBoatList(sysBoat);

            BoatMessage boatMessage = new BoatMessage(MessageType.CONFIG_MESSAGE, (byte) 1);
            WharfInfo wharfInfo = new WharfInfo();
            wharfInfo.setCreateOrUpdateTime(new Date());
            wharfInfo.setLat((double) 0);
            wharfInfo.setLon((double) 0);
            wharfInfo.setWharfCode('A');

            List<BaseDataPiece> dataPieceList = boatMessage.getDataPieceList();
            dataPieceList.add(wharfInfo);

            //向所有对应船只发送当前码头被删除的报文
            boatList.forEach(boat -> {
                SocketChannelManager.sendMsgToAssignedBoat(boat.getBoatId(), boatMessage);
                //同时将所有船只的码头id更新为0,即没有指定码头
                boat.setWharfId(0L);
                sysBoatService.updateSysBoat(boat);
            });
        }
        return toAjax(rows);
    }

    /**
     * 码头状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:wharf:edit')")
    @Log(title = "景区码头管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysWharf sysWharf) {
        sysWharf.setUpdateBy(getUsername());
        return toAjax(sysWharfService.updateWharf(sysWharf));
    }

    @GetMapping(value = "/byScenicId/{scenicId}")
    public AjaxResult getWharfListByScenicId(@PathVariable("scenicId") Long scenicId) {
        return AjaxResult.success(sysWharfService.getWharfListByScenicId(scenicId));
    }
}
